package com.bidv.wcm;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bidv.BO.PaginationBO;
import com.bidv.util.DateUtil;
import com.bidv.util.Pagination;
import com.bidv.util.StringUtil;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
import com.ibm.workplace.wcm.api.Content;
import com.ibm.workplace.wcm.api.DocumentId;
import com.ibm.workplace.wcm.api.DocumentIdIterator;
import com.ibm.workplace.wcm.api.DocumentLibrary;
import com.ibm.workplace.wcm.api.DocumentTypes;
import com.ibm.workplace.wcm.api.ImageComponent;
import com.ibm.workplace.wcm.api.TextComponent;
import com.ibm.workplace.wcm.api.WCM_API;
import com.ibm.workplace.wcm.api.Workspace;

/**
 * Servlet implementation class Search
 */
@WebServlet("/Search")
public class Search extends HttpServlet {
	private static final String SUB_TITLE = "SubTitle";
	private static final String IMAGE_SUBTITLE = "ImageSubtitle";
	private static final String DESCRIPTION_FIRST_TITLE = "description";
	private static final String IMAGE_FIRST_TITLE = "image";
	private static final String TOTAL = "total";
	private static final String HREF = "href";
	private static final String MODIFIED_DATE = "modifiedDate";
	private static final String LABEL_DOC = "label";
	private static final String DETAIL_JSP_WCM_WPS_WCM_CONNECT = "detail.jsp?wcm=/wps/wcm/connect/";
	private static final String TEMPLATE = "TempNews";

	public Search() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("application/json");
			// bien json
			PrintWriter out = response.getWriter();
			JSONArray jsonArray = new JSONArray();
			JSONObject json = null;

			int startPage = Integer.parseInt(request.getParameter("StartPage"));
			int pageSize = Integer.parseInt(request.getParameter("PageSize"));
			String library = request.getParameter("Library");
			String textSearch = request.getParameter("TextSearch");
			String jsp = request.getParameter("jsp");
			int k = 1;

			DocumentId siblingId = null;
			DocumentId authoringTmpl = null;
			DocumentId siteArea = null;
			DocumentIdIterator authoringIterator = null;
			DocumentIdIterator siteAreaIterator = null;
			DocumentId<Content> contentid = null;
			DocumentIdIterator<Content> docContent = null;
			String site = "";
			String url = "";
			String label = "";
			String image = "";
			String description = "";

			Content content = null;

			Workspace myworkspace = WCM_API.getRepository()
					.getSystemWorkspace();
			myworkspace.login();

			DocumentLibrary MyLibrary = myworkspace.getDocumentLibrary(library);
			myworkspace.setCurrentDocumentLibrary(MyLibrary);

			// find Authoring template
			authoringIterator = myworkspace.findByName(
					DocumentTypes.AuthoringTemplate, TEMPLATE);
			// get authoring template of lib
			authoringTmpl = authoringIterator.next();

			/*
			 * contentSearch(DocumentId templateId, DocumentId[] siteAreaIds,
			 * DocumentId[] categoryIds, java.lang.String[] keywords, boolean
			 * matchAllCategories, boolean includeAncestorCategories, boolean
			 * includeDescendentCategories, boolean includeAncestorSiteAreas,
			 * boolean includeDescendentSiteAreas, java.lang.String sortKey1,
			 * java.lang.String sortKey2, java.lang.String sortKey3, boolean
			 * sortAscending, int workflowStatusFilter)
			 */
			docContent = myworkspace.contentSearch(authoringTmpl, null, null,
					null, false, false, false, false, false,
					Workspace.SORT_KEY_PUBLISH_DATE, null, null, false,
					Workspace.WORKFLOWSTATUS_PUBLISHED);

			/* ket qua tim kiem */
			List<Content> lstContent = getListSearch(myworkspace, docContent,
					textSearch);

			int fromContent = pageSize * (startPage - 1);
			int toSize = Math.min(pageSize * startPage,lstContent.size());
			for (int i =fromContent; i < toSize; i++) {
				url = "";
				label = "";
				image = "";
				description = "";
				json = new JSONObject();

				content = lstContent.get(i);
				site = content.getParentId().getName();

				label = content.getTitle();

				url = DETAIL_JSP_WCM_WPS_WCM_CONNECT + library + "/" + library
						+ "/" + site + "/" + content.getName();

				ImageComponent imageComponent = (ImageComponent) content
						.getComponent(IMAGE_SUBTITLE);
				TextComponent rtDescription = (TextComponent) content
						.getComponent(SUB_TITLE);
				description = rtDescription.getText();
				if (imageComponent.getImageFileName() != null
						&& !"".equals(imageComponent.getImageFileName())) {
					image = StringUtil.replaceMyConnect(imageComponent
							.getResourceURL());
				}

				json.put(LABEL_DOC, label);
				json.put(MODIFIED_DATE, DateUtil.getDate(
						content.getModifiedDate(), DateUtil.SHORT_DATE_PATTERN));
				json.put(HREF, url);
				json.put(IMAGE_FIRST_TITLE, image);
				json.put(DESCRIPTION_FIRST_TITLE, description);
				// add vao mang jsonarray
				jsonArray.add(json);
			}

			// cau hinh va gui ket qua phan trang
			Pagination pagination = new Pagination();
			PaginationBO paginationBO = new PaginationBO();

			paginationBO.setCurrentPage(startPage);
			paginationBO.setTotalRecord(lstContent.size());
			paginationBO.setLimit(pageSize);
			paginationBO.setRange(3);
			paginationBO.setLinkFull("search.jsp?TextSearch="+textSearch+"&page={page}");
			paginationBO.setLinkFirst("search.jsp?TextSearch="+textSearch+"&page=1");

			pagination.init(paginationBO);

			json = new JSONObject();
			json.put("pagination", pagination.html());
			jsonArray.add(json);

			out.print(jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<Content> getListSearch(Workspace myworkspace,
			DocumentIdIterator<Content> docContent, String textSearch) {
		List<Content> lstResult = new ArrayList<Content>();
		DocumentId<Content> contentid = null;
		Content content = null;
		String title = "";
		try {
			if (docContent != null) {
				while (docContent.hasNext()) {
					contentid = docContent.next();
					content = myworkspace.getById(contentid);

					title = content.getTitle();

					if (textSearch != null && !"".equals(textSearch.trim())) {
						if (title.indexOf(textSearch) != -1) {
							lstResult.add(content);
						}
					} else {
						// neu chuoi dau vao bang rong thi hien thi tat ca du
						// lieu
						lstResult.add(content);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lstResult;
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

}
